import utils from '@/common/utils.js'
import menuApi from '@/api/auth/menuApi'
import {menuGroup, menuType, menuTypePDA} from '@/view/auth/dict'
import {yesOrNo} from '@/common/dict'

const menuTypeDict = menuType

export default {
  name: "Menu",
  filters: {
    typeFormat(type) {
      return menuType.map[type] || '-'
    },
    typeFormatPDA(type) {
      return menuTypePDA.map[type] || '-'
    },
    menuGroupFormat(value) {
      return menuGroup.map[value] || '-'
    }
  },
  watch: {
    'formData.group': {
      handler(value) {
        if (value) {
          menuApi.getTree({group: value}).then(res => {
            this.setMenuTree(res.data, value)
          })
        }
      },
      immediate: true,
    }
  },
  data() {
    return {
      // 是否可见
      formVisible: false,
      // 表单标题
      formTitle: '',
      // 表单状态 edit,insert
      formState: '',
      // 保存事件是否完成,避免表单重复提交
      formLoading: false,
      // table数据是否加载完成
      loading: false,
      // 表单数据
      formData: {
        id: '',
        name: '',
        group: menuGroup.enum.PC.value,
        type: '',
        parentId: '',
        path: '',
        code: '',
        icon: '',
        visible: '',
        permission: '',
        sorting: '',
        tableInfoIds: []
      },
      // 详情是否可见...
      detailVisible: false,
      // 详情数据
      detailData: {},
      // 表单验证规则
      rules: {
        name: [{required: true, message: "请输入名称", trigger: "blur"}],
        group: [{required: true, message: "请输入分组", trigger: "change"}],
        type: [{required: true, message: "请输入类型", trigger: "change"}],
        parentId: [{required: true, message: "请输入父菜单", trigger: "change"}],
        // visible: [{required: true, message: "请选择是否可见", trigger: "blur"}],
        sorting: [{required: true, message: "请输入排序", trigger: "blur"}],
      },
      currentRow: {},
      menuTree: [],
      menuTreePDA: [],
      menuTableTree: [],
      options: {
        yesOrNo: yesOrNo,
        menuType: menuType,
        menuGroup: menuGroup,
        menuTypePDA,
        // 菜单树,用于选择父菜单
        menu: {},
        tableInfoList: [],
      },
      params: {
        name: '',
        group: menuGroup.enum.PC.value,
      },
      multipleSelection: []
    }
  },
  methods: {
    handleInput() {
      this.query()
    },
    // 初始化 下拉数据的获取等
    init() {
    },
    reset() {
      this.params = {
        name: '',
        group: menuGroup.enum.PC.value,
      }
      this.query();
    },
    // 设置整个菜单树
    setMenuTree(tree, _menuGroup) {
      let menuTree = JSON.parse(JSON.stringify(tree))
      let head = [{id: '0', name: '/', type: -1}]
      menuTree = head.concat(menuTree)
      if (_menuGroup === menuGroup.enum.PC.value) {
        let queue = []
        queue.push({children: menuTree})
        while (queue.length) {
          let node = queue[0]
          if (Array.isArray(node.children)) {
            for (let i = 0; i < node.children.length; i++) {
              let e = node.children[i]
              if (e.type === menuType.enum.MENU.value || e.type === menuType.enum.ROUTE.value || e.type === -1) {
                queue.push(e)
              } else {
                node.children.splice(i, 1)
                if (!node.children.length) {
                  node.children = null
                  break
                }
                i--
              }
            }
          }
          queue.shift()
        }
        this.menuTree = menuTree
      } else if (_menuGroup === menuGroup.enum.PDA.value) {
        let queue = []
        queue.push({children: menuTree})
        while (queue.length) {
          let node = queue[0]
          if (Array.isArray(node.children)) {
            for (let i = 0; i < node.children.length; i++) {
              let e = node.children[i]
              if (e.type === menuTypePDA.enum.SERIES.value || e.type === -1) {
                queue.push(e)
              } else {
                node.children.splice(i, 1)
                if (!node.children.length) {
                  node.children = null
                  break
                }
                i--
              }
            }
          }
          queue.shift()
        }
        this.menuTreePDA = menuTree
      }
    },
    // 获取列表数据
    query() {
      this.loading = true
      menuApi.getTree(this.params).then(res => {
        this.menuTableTree = res.data
      }).catch(err => {
        this.menuTableTree = []
      }).finally(() => {
        this.loading = false
      })
    },
    // 清空表单
    formClear() {
      // 清空校验
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
        this.$refs.form.resetFields()
      }
      // 重新赋值
      if (this.params.group !== menuGroup.enum.PDA.value) {
        this.formData = {
          id: '',
          name: '',
          group: menuGroup.enum.PC.value,
          type: menuType.enum.MENU.value,
          parentId: '0',
          path: '',
          code: '',
          icon: '',
          visible: this.options.yesOrNo.enum.YES.value,
          permission: '',
          sorting: '',
          tableInfoIds: [],
        }
      } else {
        this.formData = {
          id: '',
          name: '',
          group: menuGroup.enum.PDA.value,
          type: menuTypePDA.enum.SERIES.value,
          parentId: '0',
          code: '',
        }
      }
    },
    // 保存事件
    formSave() {
      this.$refs.form.validate(valid => {
          if (valid) {
            let data = JSON.parse(JSON.stringify(utils.formatObj(this.formData)))
            if (this.formData.group === menuGroup.enum.PC.value) {
              // 关于父菜单类型的校验,菜单的父菜单是菜单,路由的父菜单是菜单,按钮的父菜单是路由
              let nodes = this.$refs.cascader.getCheckedNodes()
              // node 的长度必在0 1 之间
              let flag = false
              if (!nodes.length) {
                this.$message.warning('请选择一个父菜单')
                return
              } else {
                let node = nodes[0]
                let parentType = node.data.type
                switch (this.formData.type) {
                  case menuType.enum.MENU.value:
                    if (parentType !== menuType.enum.MENU.value && parentType !== -1) {
                      this.$message.warning('请选择一个[菜单]作为父菜单')
                      flag = true
                    }
                    break
                  case menuType.enum.ROUTE.value:
                    if (parentType !== menuType.enum.MENU.value && parentType !== -1) {
                      this.$message.warning('请选择一个[菜单]作为父菜单')
                      flag = true
                    }
                    break
                  case menuType.enum.BUTTON.value:
                    if (parentType !== menuType.enum.ROUTE.value) {
                      this.$message.warning('请选择一个[路由]作为父菜单')
                      flag = true
                    }
                }
              }
              if (flag) {
                return;
              }
              this.formLoading = true
              switch (data.type) {
                case menuType.enum.MENU.value:
                  delete (data.code)
                  delete (data.path)
                  delete (data.tableInfoIds)
                  delete (data.permission)
                  break
                case menuType.enum.ROUTE.value:
                  delete (data.permission)
                  break;
                case menuType.enum.BUTTON.value:
                  delete (data.code)
                  delete (data.path)
                  delete (data.icon)
                  delete (data.sorting)
                  // 按钮没有可见/不可见的概念,但为了列表上展示,就设置成可见...
                  break
              }
            } else if (this.formData.group === menuGroup.enum.PDA.value) {
              data = {
                id: data.id,
                name: data.name,
                code: data.code,
                group: data.group,
                type: data.type,
                parentId: data.parentId
              }
              let nodes = this.$refs.cascader.getCheckedNodes()
              // node 的长度必在0 1 之间
              let flag = false
              if (!nodes.length) {
                this.$message.warning('请选择一个父菜单')
                return
              } else {
                let parentNode = nodes[0]
                if (this.formData.type === menuTypePDA.enum.SERIES.value) {
                  if (parentNode.data.id !== '0') {
                    this.$message.warning('模块的父节点是根节点!')
                    return
                  }
                } else if (this.formData.type === menuTypePDA.enum.BUTTON.value) {
                  if (parentNode.data.type !== menuTypePDA.enum.SERIES.value) {
                    this.$message.warning('按钮的父节点是模块!')
                    return
                  }
                }
              }
            }
            if (this.formState === 'insert') {
              this.$rq.insert(menuApi.url, data).then(res => {
                this.$message.success('保存成功')
                this.formVisible = false
                this.formLoading = false
                this.query()
              }, err => {
                this.formLoading = false
              })
            } else if (this.formState === 'edit') {
              this.$rq.updateById(menuApi.url, data).then(res => {
                this.$message.success('保存成功')
                this.formVisible = false
                this.formLoading = false
                this.query()
              }, err => {
                this.formLoading = false
              })
            }

          }
        }
      )
    },
    // 表单关闭
    formClose() {
      this.formVisible = false
    }
    ,
    // 设置表单数据
    formSet(data) {
      this.formData.id = data.id
      this.formData.name = data.name
      this.formData.group = data.group
      this.formData.type = data.type
      this.formData.parentId = data.parentId
      this.formData.path = data.path
      this.formData.code = data.code
      this.formData.icon = data.icon
      this.formData.visible = data.visible
      this.formData.permission = data.permission
      this.formData.sorting = data.sorting
      this.formData.tableInfoIds = data.tableInfoIds || []
    }
    ,
//复选框事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
    ,
// 删除方法
    del() {
      if (this.multipleSelection.length) {
        let ids = this.multipleSelection.map(e => e.id)
        this.$confirm('确认删除?', {
          title: '提示',
          confirmButtonText: '删除',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              this.$rq.deleteByIds(menuApi.url, ids).then(res => {
                this.$message.success('删除成功')
                this.query()
              })
            }
          }
        })
      } else {
        this.$message.warning('请至少选择一行')
      }
    }
    ,
// 编辑
    edit(row) {
      this.formTitle = '编辑'
      this.formState = 'edit'
      this.formClear()
      this.formSet(row)
      this.formVisible = true
    },
    // 新增
    insert() {
      this.formTitle = '新增'
      this.formState = 'insert'
      this.formClear()
      this.formVisible = true
    }
    ,
    // 详情
    detail(row) {
      this.detailVisible = true
      this.detailData = row
    }
    ,
    // 关闭详情
    detailClose() {
      this.detailVisible = false
    },
    tableRowClassName({row}) {

      let className = ''
      switch (row.type) {
        case menuType.enum.MENU.value:
          className = 'menu-row'
          break;
        case menuType.enum.ROUTE.value:
          className = 'route-row'
          break;
        case menuType.enum.BUTTON.value:
          className = 'button-row'
          break;
      }
      return className
    }
  },
  mounted() {
    this.query()
  },
  created() {
    this.init()
  },
}
